#include "NetWorkProDefine.h"
#include <sys/fcntl.h>

void clientprocess(int connfd)
{
    printf("clientprocess starting.\n");
    char recvline[MAXLEN] = {0};
    while (1)
    {
        //读
        int readlen = read(connfd, recvline, MAXLEN-1);
        if (readlen < 0 && (EAGAIN == errno || EINTR == errno))
        {
            continue;
        }
        else if(readlen > 0)
        {
        //写
            int writelen = write(connfd, recvline, readlen);
            printf("sercv :%s\n", recvline);
            memset(recvline, 0, sizeof(recvline));
        }
        else
        {
            printf("read error. errno :%d\tmsg :%s\n", errno, strerror(errno));
            break;
        }
    }
    printf("end of cliendprocess.\n");
}

int main(int argc, char** argv)
{
    printf("welcome to nbserver!\n");

    struct sockaddr_in addr;

    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(SERV_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    
    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    int setcode;
    if ((setcode = setnblock(listenfd)) >= 0)
    {
        if(bind(listenfd, (SA*)&addr, sizeof(addr)) != 0
            || listen(listenfd, LISTENENQ) != 0)
        {
            printf("bind or listen error, errno :%d\tmsg :%s\n", errno, strerror(errno));
            printf("ip :%d\tport :%d\n", INADDR_ANY, SERV_PORT);
            return -1;
        }
    }
    else
    {
        printf("setnblock error, listenfd :%d\tsetcode :%d\n", listenfd, setcode);
    }
    
    struct sockaddr cliaddr;
    socklen_t cliaddrlen = sizeof(cliaddr);
    while (1)
    {
        int connfd = accept(listenfd, (SA*)&cliaddr, &cliaddrlen);
        if(connfd < 0)
        {
            if (errno != ECONNABORTED 
                && errno != EWOULDBLOCK
                && errno != EPROTO
                && errno != EINTR)
            {
                err_quit("accept error! errno :%d\tmsg :%s\n", errno, strerror(errno));
            }
            sleep(1);
            continue;
        }
        else if (connfd > 0)
        {
            display_sockaddr(&cliaddr);
            //process client
            clientprocess(connfd);
            close(connfd);
        }
    }
    close(listenfd);
    printf("end of nbserv.\n");
    return 0;
}